package com.sports.service.impl;


import com.sports.common.convertor.FavoritesReqDtoConvertor;
import com.sports.common.convertor.FavoritesResDtoConvertor;
import com.sports.domain.dto.req.FavoritesReqDto;
import com.sports.domain.dto.res.FavoritesResDto;
import com.sports.domain.po.FavoritesPo;
import com.sports.domain.po.SportsPo;
import com.sports.mapper.FavoritesMapper;
import com.sports.mapper.SportsMapper;
import com.sports.service.FavoritesService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sports.service.TokenService;
import com.google.common.base.CaseFormat;
import com.sports.common.exception.AppException;
import com.sports.common.exception.ErrorCode;
import com.baomidou.mybatisplus.ext.BasePService;
import com.baomidou.mybatisplus.ext.IPService;
import com.baomidou.mybatisplus.ext.Pager;
import com.baomidou.mybatisplus.ext.QueryParamUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
@Slf4j
@Service("favoritesAppService")
@Transactional(rollbackFor = Exception.class)
public class FavoritesServiceImpl implements FavoritesService {

    @Autowired
    private FavoritesReqDtoConvertor favoritesReqDtoConvertor;

    @Autowired
    private FavoritesResDtoConvertor favoritesResDtoConvertor;

    @Autowired
    private FavoritesMapper favoritesMapper;

    @Autowired
    private SportsMapper sportsMapper;

    @Autowired
    private TokenService tokenService;

    private IPService<FavoritesPo> favoritesPoService;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    public FavoritesServiceImpl(FavoritesMapper favoritesMapper) {
        this.favoritesPoService = new BasePService(favoritesMapper);
    }


    @Override
    public FavoritesResDto save(FavoritesReqDto reqDto) {
        FavoritesPo po = favoritesReqDtoConvertor.dto2Po(reqDto);
        favoritesPoService.save(po);
        FavoritesResDto resDto = favoritesResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public void operation(FavoritesReqDto reqDto) {
        List<FavoritesPo> favoritesPos = favoritesMapper.selectList(Wrappers.<FavoritesPo>lambdaQuery()
                .eq(FavoritesPo::getSportsId, reqDto.getSportsId())
                .eq(FavoritesPo::getType, reqDto.getType())
                .eq(FavoritesPo::getUserId, reqDto.getUserId()));
        if (CollectionUtils.isEmpty(favoritesPos)) {
            FavoritesPo po = favoritesReqDtoConvertor.dto2Po(reqDto);
            favoritesPoService.save(po);
        } else {
            for (FavoritesPo favoritesPo : favoritesPos) {
                favoritesMapper.deleteById(favoritesPo.getId());
            }
        }
    }

    @Override
    public List<FavoritesResDto> getList() {
        List<FavoritesPo> list = favoritesPoService.list();
        return favoritesResDtoConvertor.poList2DtoList(list);
    }

    @Override
    public boolean deleteByIds(String ids) {
        try {
        List<Long> idLongList =
        Arrays.asList(ids.split(",")).stream().map(s -> NumberUtils.createLong(s.trim())).collect(Collectors.toList());
        return favoritesPoService.removeByIds(idLongList);
        } catch (Exception e) {
        throw new AppException("参数错误：" + ids, ErrorCode.sys("417"), e);
        }
     }

    @Override
    public Pager<FavoritesResDto> doPager(Map<String, Object> params) {
        Pager<FavoritesPo> poPager = favoritesPoService.queryPage(params, FavoritesPo.class);
        Pager<FavoritesResDto> resDtoPager = favoritesResDtoConvertor.convertPoPager2ResDtoPager(poPager);
        for (FavoritesResDto favoritesResDto : resDtoPager.getList()) {
            if (null != favoritesResDto.getSportsId()) {
                SportsPo sportsPo = sportsMapper.selectById(favoritesResDto.getSportsId());
                if (null != sportsPo) {
                    favoritesResDto.setName(sportsPo.getTitle());
                    favoritesResDto.setUrl(sportsPo.getUrl());
                }
            }
        }
        return resDtoPager;
    }

    @Override
    public FavoritesResDto selectOne(Long id) {
        FavoritesPo po = favoritesPoService.getById(id);
        FavoritesResDto resDto = favoritesResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public FavoritesResDto selectOne(Map<String, Object> params) {
        QueryWrapper queryWrapper = QueryParamUtils.queryWrapper4eq(FavoritesPo::new, params);
        FavoritesPo po = favoritesPoService.getOne(queryWrapper);
        FavoritesResDto resDto = favoritesResDtoConvertor.po2Dto(po);
        return resDto;
    }

    @Override
    public boolean updateProps(Long id, Map<String, Object> params) {
        UpdateWrapper<FavoritesPo> updateWrapper = QueryParamUtils.updateWrapper4Map(FavoritesPo::new, id, params);
        return favoritesPoService.update(new FavoritesPo(), updateWrapper);
        }

    @Override
    public boolean updateProps(Long id, FavoritesReqDto reqDto) {
        FavoritesPo po = favoritesReqDtoConvertor.dto2Po(reqDto);
        po.setId(id);
        return favoritesPoService.updateById(po);
    }


    @Override
    public boolean updateAllProps(Long id, FavoritesReqDto reqDto) {
        UpdateWrapper<FavoritesPo> updateWrapper = Wrappers.update();
        updateWrapper.eq("id", id);
        Field[] fields = FavoritesReqDto.class.getDeclaredFields();
        Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).forEach(field -> {
        try {
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(field.getName(), FavoritesReqDto.class);
        Method getMethod = propertyDescriptor.getReadMethod();
        String fileNameCamel = getMethod.getName().substring(3);
        String fileNameUnderline = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, fileNameCamel);
        updateWrapper.set(fileNameUnderline, getMethod.invoke(reqDto));
        } catch (Exception ex) {
        log.warn("属性不存在get方法："+field.getName(),ex);
        }
        });
        return favoritesPoService.update(new FavoritesPo(), updateWrapper);
    }

}